# -*- coding: utf-8 -*-
#
# fusion.feed.feedgenerator
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Harri Hämäläinen <harri.hamalainen@helsinki.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import xml.etree.ElementTree as ET
import fusion.feed.json2xml as json2xml
from fusion.db.db import DB
from fusion.http.server import MAIN
from simplejson import loads
from xml.sax.saxutils import escape

ET._namespace_map['http://p2p-fusion.org/2007/fusion/'] = 'fusion'
ET._namespace_map['http://www.w3.org/2005/Atom'] = 'atom'
ET._namespace_map['http://purl.org/dc/elements/1.1/'] = 'dc'

MAXIMUM_TAG_LENGTH = 20

__all__ = ['FeedGenerator']

class FeedGenerator(object):

    def __init__(self, db=None, collection_id=None, create_summary='False', entries_path='', tags_path='', comments_path=''):
        self.db = db
        self.collection = collection_id
        self.create_summary = create_summary
        self.entries_path = entries_path
        self.tags_path = tags_path
        self.comments_path = comments_path

    # get single entry as XML 
    def get_entry(self, entry_id):
        xml_entry = self._create_entry(entry_id)
        if xml_entry is None:
            return None
        return ET.tostring(xml_entry)

    def get_feed(self):
        self._create_feed_body()
        self._create_feed_entries()
        return ET.tostring(self.root)
 
    def _create_entry(self, entry_path):
        try:
            self.root = ET.Element("entry")
            self.root.set('xmlns', 'http://www.w3.org/2005/Atom')
            v = self.db.get(self.collection, self.entries_path+entry_path)
            p = self.entries_path+entry_path
            json = loads(v)
            json2xml.to_xml(json, self.root)
            return self.root
        except:
            pass

    def _create_feed_body(self):
        self.root = ET.Element("feed")
        self.root.set('xmlns', 'http://www.w3.org/2005/Atom')
        id = ET.SubElement(self.root, "id")
        id.text = 'tag:hiit.fi,2007-06:atom_feed'
        title = ET.SubElement(self.root, "title")
        title.text = self.db.get(self.collection, "info/title")

    def _get_popular_tags(self, json_tags, limit=5):
        tagdict = {}
        result = []
        for key in json_tags:
            if not tagdict.has_key(key):
                tagdict[key] = 1;
            else:
                tagdict[key] += 1;

        for i in range(len(tagdict)) and range(limit):
            greatest = None
            for key in tagdict:
                if len(key) > MAXIMUM_TAG_LENGTH: continue
                if greatest is None or tagdict[key] > tagdict[greatest]: 
                    greatest = key

            if greatest is not None:
                result.append(greatest)
                del tagdict[greatest]
        return result

    def _remove_duplicates_and_empties(self, array):
        obj = {}
        ret = []
        for index in array:
            obj[index] = True
        for key in obj:
            if key != '':
                ret.append(key.lower())
        return ret

    def _get_entry_tags(self, entry_path):
        json_tags = []
        for tag in self.db.keys(self.collection, key_prefix=self.tags_path):
            if tag.find(entry_path) >= 0:
                try:
                    json = loads(self.db.get(self.collection, self.tags_path+tag))
                    if isinstance(json, list):
                        json = self._remove_duplicates_and_empties(json)
                        json_tags += json
                except:
                    continue

        return self._get_popular_tags(json_tags)

    def _get_entry_comments(self, entry_path):
        comment_line = []
        for comment in self.db.keys(self.collection, key_prefix=self.comments_path):
            if comment.find(entry_path) >= 0:
                try:
                    comment_json = loads(self.db.get(self.collection, self.comments_path+comment))
                    comment_line.append(escape(comment_json['author']['name']+': '+comment_json['content']))
                except (KeyError, ValueError, TypeError):
                    continue

        return comment_line

    def _create_feed_entries(self):
        entries = [entry for entry 
            in self.db.keys(self.collection, key_prefix=self.entries_path)]

        most_recent = None;
        update_tag = ET.SubElement(self.root, "updated")
        for entry in entries:
            if self.tags_path:
                tags = self._get_entry_tags(entry)
            if self.comments_path:
                comments = self._get_entry_comments(entry)

            try:
                json = loads(self.db.get(self.collection, self.entries_path+entry))
            except:
                continue
    
            try:
                if most_recent is None or json['published'] > most_recent:
                    most_recent = json['published']
            except:
                pass

            if isinstance(tags, list): 
                tags = escape(','.join(tags))+'\n'
            else: 
                tags = ''

            try:
                for link in json['link']:
                    if link['rel'] == 'enclosure' and link['href'].startswith('/'):
                        link['href'] = MAIN+link['href']
            except: pass

            if self.create_summary:
                json['summary'] = { 'type': 'html'}
                json['summary']['$t'] = ''
                if self.tags_path:
                    json['summary']['$t'] += '<b>Tags:</b> ' + tags + '<br />'

                try:
                    json['summary']['$t'] += '<b>Content:</b><br /> ' + json['content']
                except (KeyError, ValueError): pass

                if self.comments_path:
                    json['summary']['$t'] += '<br /><b>Comments:</b><br />'+'<br />\n'.join(comments)

            entry = ET.SubElement(self.root, "entry")
            json2xml.to_xml(json, entry)

        update_tag.text = most_recent
